package com.sentinel.demo.basic.common;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dsy on 2019/12/12
 */
public class InitRuleUtils {

    /**
     * 限流规则
     * @param resource
     */
    public static void initFlowQpsRule(String resource) {
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource(resource);
        // set limit qps to 20
        rule1.setCount(3);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setLimitApp("default");
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }

    /**
     * 降级规则
     * @param resource
     */
    public static void initDegradeRule(String resource ,int ruleType ,int count ,int timeWindow ,int requestAmount) {
        List<DegradeRule> rules = new ArrayList<DegradeRule>();
        DegradeRule rule = new DegradeRule();
        rule.setResource(resource);
        // set limit exception count to 4
        rule.setCount(count);
//        RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT ;
//        RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO ;
//        RuleConstant.DEGRADE_GRADE_RT ;
        rule.setGrade(ruleType);
        rule.setTimeWindow(timeWindow);
        rule.setMinRequestAmount(requestAmount);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}
